<template>
  <div class="echarts">
    <div class="title">统计周期：
    <DatePicker
          style="width: 300px"
          type="daterange"
          ref="createDatePicker"
          split-panels
          transfer
          format="yyyy-MM-dd"
          placeholder="请选择"
          :value="queryDateRange"
          @on-change="onQueryDateRangeChange"
      ></DatePicker>
      <span style='font-size:12px;color: #2d8cf0'> * 默认显示最近一个月的数据</span>
    </div>
    <!-- <Row :gutter="20">
      <Col :xs="12" :md="8" :lg="4" v-for="(infor, i) in inforCardData" :key="`infor-${i}`" style="height: 120px;padding-bottom: 10px;">
        <infor-card shadow :color="infor.color" :icon="infor.icon" :icon-size="36">
          <count-to :end="infor.count" count-class="count-style"/>
          <p>{{ infor.title }}</p>
        </infor-card>
      </Col>
    </Row> -->
    <Row :gutter="20" style="margin-top: 10px;">
      <Col :md="12" :lg="12" style="margin-bottom: 20px;">
        <Card shadow>
          <chart-pie style="height: 300px;" :value="numData" text="订单笔数" :subtext="true"></chart-pie>
        </Card>
      </Col>
      <Col :md="12" :lg="12" style="margin-bottom: 20px;">
        <Card shadow>
          <chart-pie style="height: 300px;" :value="pieData" text="订单金额" v-if="pieData" :subtext="false"></chart-pie>
        </Card>
      </Col>
    </Row>
    <Row :gutter="20" style="margin-top: 10px;">
      <Col :md="12" :lg="12" style="margin-bottom: 20px;">
        <Card shadow>
          <chart-bar style="height: 300px;" :value="barData2" text="各业务交易订单数" />
        </Card>
      </Col>
      <Col :md="12" :lg="12" style="margin-bottom: 20px;">
      <Card shadow>
        <chart-bar style="height: 300px;" :value="barData1" text="各业务交易金额" />
      </Card>
      </Col>
    </Row>
    <!-- <Row :gutter="20" style="margin-top: 10px;">
      <Col :md="12" :lg="12" style="margin-bottom: 20px;">
      <Card shadow>
        <chart-bar style="height: 300px;" :value="barData3" :color="['#ED7D31']" text="退款统计" />
      </Card>
      </Col>
    </Row> -->
    <!-- <Row>
      <Card shadow>
        <example style="height: 310px;"/>
      </Card>
    </Row> -->
  </div>
</template>

<script>
  import {
    Button,
    Input,
    Modal,
    Message,
    Col,
    Row,
    Form,
    FormItem,
    DatePicker,
    Select,
    Option,
    Card
  } from "view-design";
  import { namespace } from "../module/echartModule";
  import InforCard from '@/components/info-card';
  import CountTo from '@/components/count-to';
  import SearchBar from "@/components/SearchBar";
  import {
    ChartPie,
    ChartBar
  } from '@/components/charts'
  // import Example from './example.vue'
  export default {
    name: 'home',
    components: {
      SearchBar,
      SearchBarItem: SearchBar.SearchBarItem,
      InforCard,
      CountTo,
      ChartPie,
      ChartBar,
      // Example,
      Button,
      Input,
      Modal,
      Message,
      Col,
      Row,
      Form,
      FormItem,
      DatePicker,
      Select,
      Option,
      Card
    },
    data() {
      return {
        queryDateRange:[],
        businessList:[],
        dataModule: {},
        // inforCardData: [{
          //     title: '新增用户',
          //     icon: 'md-person-add',
          //     count: 803,
          //     color: '#2d8cf0'
          //   },
          //   {
          //     title: '累计点击',
          //     icon: 'md-locate',
          //     count: 232,
          //     color: '#19be6b'
          //   },
          //   {
          //     title: '新增问答',
          //     icon: 'md-help-circle',
          //     count: 142,
          //     color: '#ff9900'
          //   },
          //   {
          //     title: '分享统计',
          //     icon: 'md-share',
          //     count: 657,
          //     color: '#ed3f14'
          //   },
          //   {
          //     title: '新增互动',
          //     icon: 'md-chatbubbles',
          //     count: 12,
          //     color: '#E46CBB'
          //   },
          //   {
          //     title: '新增页面',
          //     icon: 'md-map',
          //     count: 14,
          //     color: '#9A66E4'
          //   }
        // ],
        numData: [],
        pieData: [],
        stateDate: '', // 头部时间
        endDate: '', // 头部时间
        barData1: {},
        barData2: {},
        // barData3: {
        //   '门票': 12345,
        //   '机票': 46464,
        //   '酒店': 49797,
        //   '租车': 16464
        // },
        order: {},
        refundOrder: {},
      }
    },
    created () {
      this.getDateNew();
      this.$nextTick(()=>{
        Promise.all([this.getQueryTotal(), this.getRefundQueryTotal()]).then((resolve) => {
          let order = Number(resolve[0].count);
          let orderPay = Number(resolve[0].total);
          let refundOrdersDetail = Number(resolve[1].count);
          let refundPay = Number(resolve[1].total);
          this.numData = [{name: '订单', value: order ,isInteger:true},{name: '退款', value: refundOrdersDetail,isInteger:true}];
          this.pieData = [{name: '订单(元)', value: orderPay / 100},{name: '退款(元)', value: refundPay / 100}];
        }).catch((reject) => {
          this.$Message.error({
            content: '查询异常'
          })
        })
      })
      this.getquerySourceTotal();

    },
    methods: {
      getDate () {
        var myDate=new Date();
        const startM=(myDate.getMonth()+1)<10?'0'+(myDate.getMonth()+1):(myDate.getMonth()+1)
        const endM=(myDate.getMonth())<10?'0'+(myDate.getMonth()):(myDate.getMonth())
        const day=myDate.getDate()<10?'0'+myDate.getDate():myDate.getDate()
        this.endDate = myDate.getFullYear() + "-" + startM + "-" + day;
        // myDate.setMonth(myDate.getMonth()-1);
        this.stateDate = myDate.getFullYear() + "-" + endM + "-" + day;
        this.queryDateRange=[this.stateDate,this.endDate]
      },
      getDateNew(){
        var lastMonthToday = new Date(new Date().getTime() - 30 * 24 * 60 * 60 * 1000);
      var lastMonthYear = lastMonthToday.getFullYear();
      var lastMonth = (lastMonthToday.getMonth() + 1)<10?'0'+(lastMonthToday.getMonth() + 1):(lastMonthToday.getMonth() + 1);
      var lastMonthDay =
        lastMonthToday.getDate() < 10
          ? "0" + lastMonthToday.getDate()
          : lastMonthToday.getDate();

      this.stateDate= lastMonthYear + "-" + lastMonth + "-" + lastMonthDay;

      var myDate=new Date();
        const startM=(myDate.getMonth()+1)<10?'0'+(myDate.getMonth()+1):(myDate.getMonth()+1)
        const day=myDate.getDate()<10?'0'+myDate.getDate():myDate.getDate()
      this.endDate = myDate.getFullYear() + "-" + startM + "-" + day;
      this.queryDateRange=[this.stateDate,this.endDate]
      },
      onQueryDateRangeChange(date){
        const self=this
        this.queryDateRange=date
        this.$nextTick(() => {
          Promise.all([this.getQueryTotal(), this.getRefundQueryTotal()]).then((resolve) => {
          let order = Number(resolve[0].count);
          let orderPay = Number(resolve[0].total);
          let refundOrdersDetail = Number(resolve[1].count);
          let refundPay = Number(resolve[1].total);
          this.numData = [{name: '订单',value:order,isInteger:true },{name: '退款', value: refundOrdersDetail,isInteger:true}];
          this.pieData = [{name: '订单(元)', value: orderPay / 100},{name: '退款(元)', value: refundPay / 100}];
        }).catch((reject) => {
          this.$Message.error({
            content: error
          })
        })
        })
        this.getquerySourceTotal()
      },
      // 获取日期区间查询条件
      getQueryDataParams(){
        if(!this.queryDateRange || !this.queryDateRange.length) {
          return {}
        }
        return {startDate:this.queryDateRange[0],endDate:this.queryDateRange[1]}
      },

      // 统计订单的金额、数量
      getQueryTotal () {
        return new Promise((resolve, reject) => {
          let params = {
            orderStatus: '',
            startDate: '2024-04-20',
            endDate: '2024-05-20'
          }
          this.$store.dispatch(`${namespace}/getQueryTotal`,this.getQueryDataParams()).then((res)=>{
             if (res.data.ret === 0) {
               let data = res.data.data;
               resolve(data);
             }
          })
        })
      },
      // 统计退款的金额、数量
      getRefundQueryTotal () {
        let params = {
          refundStatus: '',
          startDate: this.stateDate,
          endDate: this.endDate
        }
        return new Promise((resolve, reject) => {
          this.$store.dispatch(`${namespace}/getRefundQueryTotal`,this.getQueryDataParams()).then((res)=>{
            console.log(res, 'data')
            if (res.data.ret === 0) {
                  let data = res.data.data;
                  resolve(data)
              }
          })
        })
      },
      // 业务渠道分组统计订单的金额、数量
      async getquerySourceTotal () {
        try {
          // let params = {
          //   orderSource: '',
          //   orderStatus: '',
          //   startDate: this.stateDate,
          //   endDate: this.endDate
          // }
          let res = await this.$store.dispatch(`${namespace}/getquerySourceTotal`,this.getQueryDataParams());
          if (res.data.ret === 0) {
            let data = res.data.data;
            let moneyCount = {};
            let orderCount = {};
            for (let i = 0; i < data.length; i++) {

              for(const item in data[i]){
                if( item === 'total' ) {
                  moneyCount[data[i]['orderSource']] = data[i][item] / 100;
                }

                if( item === 'count' ) {
                  orderCount[data[i]['orderSource']] = data[i][item];
                }
              }

            }
            this.barData1 = moneyCount; /** 交易金额 */
            this.barData2 = orderCount; /** 交易订单数 */
          }
        } catch (error) {
          this.$Message.error({
            content: error
          })
        }
      },
      handleSearch() {
        // this.$store.dispatch(`${namespace}/query`, {
        //   limit: {
        //     currentPage: 1
        //   }
        // });
      },
      resetForm() {
        this.$refs['formArea'].resetFields()
      }
    },
    mounted() {
      //
    }
  }
</script>

<style lang="less" scoped>
.echarts{
  .title {
    width: 100%;
    height: 40px;
    background: #fff;
    line-height: 40px;
    padding-left: 20px;
  }
}
  .count-style {
    font-size: 50px;
  }
</style>
